package com.biao.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

public class Demo01_Thread {
    public static void main(String[] args) {
        // 项目中禁止自己new Thread，必须使用线程池
        /*
        new Thread(() -> {

        }).start();
         */

        // 创建线程的方式：这四种实际项目中不会使用，原因可以自己看下源码
        /*
        Executors.newCachedThreadPool();    // 可缓存线程池
        Executors.newFixedThreadPool();     // 可定长度
        Executors.newScheduledThreadPool();     // 可定时
        Executors.newSingleThreadExecutor();    // 单例
         */

        // 使用手写的线程池
        Demo01_Thread executors = new Demo01_Thread(2, 10);
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executors.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "," + finalI);
                }
            });
        }
        isRun = false;
    }

    // 手写线程池
    private List<WorkThread> workThreads;
    private BlockingDeque<Runnable> runnableDeque;  // 定义队列，泛型里放线程
    private static boolean isRun = true;   // 设置线程停止

    public Demo01_Thread(int maxThreadCount, int dequeSize) {
        // 使用有序队列
        runnableDeque = new LinkedBlockingDeque<>(dequeSize);   // 设置队列大小
        workThreads = new ArrayList<>(maxThreadCount);  // 设置线程大小
        for (int i = 0; i < maxThreadCount; i++) {  // 使用循环new多个线程，执行start方法
            new WorkThread().start();
        }
    }

    class WorkThread extends Thread {   // 继承 Thread，定义线程类
        @Override
        public void run() {
            while (isRun || runnableDeque.size() > 0) {
                Runnable runnable = runnableDeque.poll();   // 队列中取线程任务
                if (runnable != null) {     // 线程不为空就执行
                    runnable.run();
                }
            }
        }
    }

    public boolean execute(Runnable command) {
        return runnableDeque.offer(command);
    }

}
